<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form :model="formdata"
               label-position="right"
               ref="formdataRef"
               label-width="150px"
               :rules='formdataRules'
               :disabled="isFormDisabled">
        <el-form-item label="标题："
                      prop="title">
          <el-input placeholder="请输入标题"
                    v-model="formdata.title"
                    clearable
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="摘要："
                      prop="summary">
          <el-input placeholder="请输入摘要"
                    v-model="formdata.summary"
                    clearable
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="广告类型："
                      prop="type">
          <el-select v-model="formdata.type"
                     clearable
                     class="w-200"
                     placeholder="请选择广告类型"
                     :disabled="isDisabled"
                     @change="changeAdType">
            <el-option v-for="item in adTypeList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期："
                      prop="termOfValidity">
          <el-input placeholder="请输入有效期"
                    v-model="formdata.termOfValidity"
                    clearable
                    class="w-200"
                    :disabled="formdata.type === 1"
                    :min="-1"><span slot="append"
                                    v-if="formdata.termOfValidity !== '永久'">天</span></el-input>
        </el-form-item>
        <el-form-item label="投放端口："
                      prop="port">
          <el-select v-model="formdata.port"
                     class="w-200"
                     placeholder="请选择投放端口"
                     @change="changePort"
                     :disabled="isDisabled">
            <el-option v-for="item in portList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="位置类型："
                      prop="positionType">
          <el-select v-model="formdata.positionType"
                     class="w-200"
                     filterable
                     placeholder="请选择位置类型"
                     @change="changePositionType"
                     :disabled="isDisabled">
            <el-option v-for="item in positionTypeList"
                       :key="item.type"
                       :label="item.name"
                       :value="item.type">
            </el-option>
          </el-select>
          <template v-if="formdata.positionType === 15">
            <el-select v-model="formdata.positionChildType"
                       clearable
                       class="w-200"
                       placeholder="请选择位置类型"
                       :disabled="isDisabled">
              <el-option v-for="item in positionChildTypeList"
                         :key="item.type"
                         :label="item.name"
                         :value="item.type">
              </el-option>
            </el-select>
          </template>
          <!--        病种详情-->
          <template v-if="formdata.positionType === 41||formdata.positionType === 44||formdata.positionType === 39">
            <el-select v-model="formdata.advertisementRelations"
                       clearable
                       class="w-200"
                       multiple
                       filterable
                       placeholder="请选择病种">
              <el-option v-for="item in diseaseDataSource"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </template>

          <!--        生命圆盘常测项-->
          <template v-if="formdata.positionType === 36">
            <el-select v-model="formdata.advertisementRelations"
                       clearable
                       class="w-200"
                       multiple
                       filterable
                       placeholder="请选择主题">
              <el-option v-for="item in themeDataSource"
                         :key="item.id"
                         :label="item.themeName"
                         :value="item.id">
              </el-option>
            </el-select>
          </template>

          <!--        慢病相关广告-->
          <template v-if="formdata.positionType === 45||formdata.positionType === 46||formdata.positionType === 47">
            <el-select v-model="formdata.advertisementRelations"
                       clearable
                       class="w-200"
                       multiple
                       filterable
                       placeholder="请选择慢病签约疾病">
              <el-option v-for="item in chronicDiseaseDataSource"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>

        <!--        指征详情-->
        <el-form-item label="指征详情：" v-if="formdata.positionType === 37||formdata.positionType === 38">
          <el-select v-model="pointerData.pointerType"
                     class="w-200"
                     placeholder="请选择指征类型"
                     value-key="id"
                     @change="handleChangePoint">
            <el-option v-for="item in pointerTypeList"
                       :key="item.id"
                       :label="item.name"
                       :value="item">
            </el-option>
          </el-select>
          <el-select v-model="pointerData.themeObj"
                     class="w-200"
                     value-key="id"
                     filterable
                     placeholder="请选择主题"
                     @change="handleChangeTheme">
            <el-option v-for="item in themeDataSource"
                       :key="item.id"
                       :label="item.themeName"
                       :value="item">
            </el-option>
          </el-select>

          <el-select v-model="pointerData.pointObj"
                     clearable
                     class="w-200"
                     multiple
                     filterable
                     value-key="pointId"
                     placeholder="请选择指征">
            <el-option v-for="item in pointerDataSource"
                       :key="item.pointId"
                       :label="item.pointName"
                       :value="item">
            </el-option>
          </el-select>
          <el-button type="primary" @click="handleOption('add_point')">新 增</el-button>

        </el-form-item>
        <el-form-item v-if="formdata.positionType === 37||formdata.positionType === 38">
          <element-table :columns="pointerColumns"
                         height="360"
                         :data="formdata.advertisementRelations">
            <template v-slot:serialNumber="{row,index}">{{ index + 1 }}</template>
            <template v-slot:option="{row,index}">
              <el-button type="danger" @click="handleOption('del_disease_edit',index)">删除
              </el-button>
            </template>
          </element-table>

        </el-form-item>


        <!--        健康地图项目编辑-->
        <el-form-item label="选择指标：" v-if="formdata.positionType === 43||formdata.positionType === 42">
          <el-select v-model="inputData.inputDiseasesId"
                     filterable
                     class="w-200"
                     placeholder="请选择病种"
                     @change="handleChangeDiseases">
            <el-option v-for="item in diseaseDataSource"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="inputData.inputTargetObj"
                     class="w-200"
                     filterable
                     value-key="id"
                     multiple
                     placeholder="请选择指标">
            <el-option v-for="item in targetDataSource"
                       :key="item.id"
                       :label="item.projectName"
                       :value="item">
            </el-option>
          </el-select>
          <el-button type="primary" @click="handleOption('add_disease_edit')">新 增</el-button>
        </el-form-item>
        <el-form-item v-if="formdata.positionType === 43||formdata.positionType === 42">
          <element-table :columns="healthMapColumns"
                         height="360"
                         :data="formdata.advertisementRelations">
            <template v-slot:serialNumber="{row,index}">{{ index + 1 }}</template>
            <template v-slot:option="{row,index}">
              <el-button type="danger" @click="handleOption('del_disease_edit',index)">删除
              </el-button>
            </template>
          </element-table>

        </el-form-item>


        <el-form-item label="是否显示"
                      prop="isShow">
          <el-radio-group v-model="formdata.isShow">
            <el-radio :label="item.id"
                      :key="item.id"
                      v-for="(item) in isShowList">{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="对应广告位图片："
                      class="is-required">
          <el-upload multiple
                     :limit=limitImgNum
                     :action="imageUploadUrl"
                     accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                     list-type="picture-card"
                     :on-success="(response, file, fileList) => handlePictureCardPreview(response, file, fileList, uploadIndex)"
                     :file-list='formdata.detailsImg'
                     :on-exceed='onexceed'
                     :on-remove='onremove'
                     :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="图片相关：">
          <el-table border
                    :data="advertisementImgDtos">
            <el-table-column label="图片"
                             width="150"
                             align="center">
              <template slot-scope="scope">
                <el-image class="setImg"
                          :src="scope.row.url"
                          :preview-src-list="[scope.row.url]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="宽度"
                             align="center"
                             width="250">
              <template slot-scope="scope">
                <el-input v-model="scope.row.wide"
                          class="w-200"
                          placeholder="请输入图片宽度"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="高度"
                             align="center"
                             width="250">
              <template slot-scope="scope">
                <el-input v-model="scope.row.high"
                          class="w-200"
                          placeholder="请输入图片高度"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="排序"
                             align="center"
                             width="250">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.position"
                                 class="w-200"
                                 placeholder="请输入图片排序"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="链接"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.link"
                          type="textarea"
                          placeholder="请输入图片链接"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="医院名称："
                      v-if="formdata.type === 1 && formdata.port === 5 || formdata.type === 2 && formdata.port === 5">
          <el-autocomplete class="w-200"
                           v-model="formdata.hospitalName"
                           placeholder="请输入医院名称"
                           :fetch-suggestions="querySearchAsync"
                           @select="handleSelect"></el-autocomplete>
        </el-form-item>
        <!---------------------- 精准营销 S------------------------>
        <div v-if="formdata.type === 2">
          <el-form-item label="投放客户："
                        v-if="formdata.port !== 1 && formdata.port !== 5">
            <el-input :placeholder="placeholderText"
                      style="width:280px"
                      v-model="formdata.organName"></el-input>
            <el-button type="primary"
                       @click="searchCustomersList">查 询
            </el-button>
            <el-table border
                      :data="tableCustomersList"
                      class="mt-20"
                      style="width:50%">
              <el-table-column label="分店名称"
                               prop="name"
                               align="center"
                               v-if="formdata.port === 3"></el-table-column>
              <el-table-column label="姓名"
                               prop="name"
                               align="center"
                               v-if="formdata.port === 2 || formdata.port === 4"></el-table-column>
              <el-table-column label="账号"
                               align="center"
                               prop="phone"></el-table-column>
              <el-table-column label="操作"
                               align="center">
                <template slot-scope="scope">
                  <el-button type="primary"
                             @click="isPutAd(scope.row, 'sure', scope.$index)">投 放
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="已选客户："
                        v-if="formdata.port !== 1 && formdata.port !== 5">
            <el-table border
                      :data="tableHaveCustomersList"
                      class="mt-20"
                      style="width:50%">
              <el-table-column label="分店名称"
                               align="center"
                               prop="name"
                               v-if="formdata.port === 3"></el-table-column>
              <el-table-column label="姓名"
                               prop="name"
                               align="center"
                               v-if="formdata.port === 2 || formdata.port === 4"></el-table-column>
              <el-table-column label="账号"
                               align="center"
                               prop="phone"></el-table-column>
              <el-table-column label="操作"
                               align="center">
                <template slot-scope="scope">
                  <el-button type="primary"
                             @click="isPutAd(scope.row, 'cancel', scope.$index)">取消投放
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <!-------------- 精准营销沃慧管 E-------------->
          <template v-if="formdata.port === 3">
            <el-form-item>
              <el-checkbox @change="changeChecked"
                           v-model="checked"
                           :label="1">对应b端客户使用爱追客的用户对应个人版pp广告投放
              </el-checkbox>
            </el-form-item>
            <template v-if="checked">
              <el-form-item label="位置类型："
                            prop="positionType">

                <el-select v-model="loveCustomersDtos.positionType"
                           clearable
                           class="w-200"
                           placeholder="请选择位置类型">
                  <el-option v-for="item in positionTypeListB"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="是否显示"
                            prop="isShow">
                <el-radio-group v-model="loveCustomersDtos.isShow">
                  <el-radio :label="item.id"
                            :key="item.id"
                            v-for="(item) in loveCustomersShowList">{{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="对应广告位图片："
                            prop="loveCustomersDtos.detailsImg">
                <el-upload multiple
                           :limit=limitImgNum
                           :action="imageUploadUrl"
                           accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                           list-type="picture-card"
                           :on-success="(response, file, fileList) => handlePictureCardPreview1(response, file, fileList, uploadIndex)"
                           :file-list='loveCustomersDtos.detailsImg'
                           :on-exceed='onexceed1'
                           :on-remove='onremove1'
                           :before-upload="beforeAvatarUpload1">
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="图片相关：">
                <el-table border
                          :data="loveCustomersDtos.advertisementImgDtos">
                  <el-table-column label="图片"
                                   width="150"
                                   align="center">
                    <template slot-scope="scope">
                      <el-image class="setImg"
                                :src="scope.row.url"
                                :preview-src-list="[scope.row.url]">
                      </el-image>
                    </template>
                  </el-table-column>
                  <el-table-column label="宽度"
                                   align="center"
                                   width="250">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.wide"
                                class="w-200"
                                placeholder="请输入图片宽度"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="高度"
                                   align="center"
                                   width="250">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.high"
                                class="w-200"
                                placeholder="请输入图片高度"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="排序"
                                   align="center"
                                   width="250">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.position"
                                       class="w-200"
                                       placeholder="请输入图片排序"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="链接"
                                   align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.link"
                                type="textarea"
                                placeholder="请输入图片链接"></el-input>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </template>
          </template>

          <el-form-item v-if="formdata.port === 1"
                        label="请选择客户区域：">

            <el-button type="primary"
                       @click="addArea">新 增
            </el-button>
            <el-table :data="tableDataSelect"
                      border
                      class="mt-20 table-select-reagion">
              <el-table-column>
                <template slot-scope="scope">
                  <el-select v-model="scope.row.region"
                             class="w-200"
                             @change="changeProvice(scope.$index)">
                    <el-option v-for="item in provinceList"
                               :value="item.id"
                               :key="item.id"
                               :label="item.name"></el-option>
                  </el-select>
                  <el-button type="danger"
                             @click="delArea(tableDataSelect, scope.$index)">删 除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>

      </el-form>
      <p align="center">
        <el-button @click="modalClose">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm"
                   v-if="!this.isDetail">保 存
        </el-button>
      </p>
    </el-dialog>
  </div>
</template>

<script>
import ElementTable from "../../../../base/ElementTable";

export default {
  props: {
    bannerObj: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    },
    getList: {
      type: Function,
      default: null
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  name: 'bannerDialog', // banner广告
  data() {
    return {
      title: '新 增',
      loading: false,
      // imageUploadUrl: this.api.file.upload,
      imageUploadUrl: this.api.appUpgradeUpload.url,
      placeholderText: '请输入投放客户!',
      diseaseDataSource: [],
      targetDataSource: [],
      themeDataSource: [],
      chronicDiseaseDataSource: [],
      pointerDataSource: [],
      inputData: {
        inputDiseasesId: '',
        inputTargetObj: []
      },
      pointerData: {
        pointerType: '',
        themeObj: '',
        pointObj: []
      },
      pointerTypeList: [
        {
          name: '基础信息',
          id: 1
        },
        {
          name: '量表自测',
          id: 2
        },
        {
          name: '常测项',
          id: 3
        }
      ],
      formdata: {
        title: '', // 标题
        summary: '', // 摘要
        type: '', // 广告类型
        termOfValidity: null, // 有效期 -1 表示永久 单位天 普通广告默认-1
        port: '', // 投放端口
        positionType: '', // 位置类型
        isShow: 0, // 0 显示 1 不显示
        detailsImgUrl: [], // 详情图片
        detailsImg: [],
        hospitalId: null,
        hospitalName: '',
        userIds: [],
        organName: '',
        region: '',
        advertisementRelations: []
      },
      loveCustomersDtos: {
        id: '',
        positionType: -1, // 位置类型
        isShow: 0, // 是否显示
        detailsImgUrl: [], // 详情图片
        detailsImg: [],
        advertisementImgDtos: []
      },
      formdataRules: {
        title: [{required: true, message: '请输入标题', trigger: 'blur'}],
        summary: [{required: true, message: '请输入摘要', trigger: 'blur'}],
        type: [{required: true, message: '请选择广告类型', trigger: 'change'}],
        termOfValidity: [
          {required: true, message: '请输入有效期', trigger: 'blur'},

        ],
        port: [{required: true, message: '请选择投放端口', trigger: 'change'}],
        positionType: [{required: true, message: '请选择位置类型', trigger: 'change'}],
        // detailsImg: [{required: true,type:'array', message: '请上传图片', trigger: 'change'}],
        // 'loveCustomersDtos.detailsImgUrl': [{required: true,type:'array',  message: '请上传图片', trigger: 'change'}],
      },

      // 广告类型列表
      adTypeList: [
        {id: 1, name: '普通广告'},
        {id: 2, name: '精准营销'}
      ],
      // 投放端口列表
      portList: [],
      // 位置类型列表
      positionTypeList: [],
      // 位置类型-子模块
      positionChildTypeList: [],
      // B端位置类型列表
      positionTypeListB: [
        {id: 4, name: '首页轮播'}
      ],
      // 是否显示列表
      isShowList: [
        {id: 1, name: '是'},
        {id: 0, name: '否'}
      ],
      advertisementImgDtos: [],
      uploadIndex: 1,
      limitImgNum: 27,
      isDisabled: false,
      isFormDisabled: false,
      tableCustomersList: [], // 投放客户列表
      tableHaveCustomersList: [], // 已选客户客户列表
      checked: 0, // b端客户使用爱追客
      loveCustomersShowList: [
        {id: 1, name: '是'},
        {id: 0, name: '否'}
      ],
      provinceList: [],
      tableDataSelect: [],
      regionList: [],
      prop: {},
      pointerColumns: [
        {
          label: '序号',
          prop: 'serialNumber',
          align: 'center',
          isSlot: true,
        }, {
          label: '类型',
          prop: 'relationType',
          align: 'center',
          formatter: (row, cellValue) => {
            switch (row.relationType) {
              case 1:
                return '基础信息'
                break
              case 2:
                return '量表自测'
                break
              case 3:
                return '常测项'
                break
            }
          },
        }, {
          label: '主题名称',
          prop: 'relationParentName',
          align: 'center'
        }, {
          label: '指标名称',
          prop: 'relationName',
          align: 'center'
        }, {
          label: '操作',
          prop: 'option',
          align: 'center',
          isSlot: true
        }
      ],
      healthMapColumns: [
        {
          label: '序号',
          prop: 'serialNumber',
          align: 'center',
          isSlot: true,
        }, {
          label: '病种名称',
          prop: 'relationParentName',
          align: 'center'
        }, {
          label: '指标名称',
          prop: 'relationName',
          align: 'center'
        }, {
          label: '操作',
          prop: 'option',
          align: 'center',
          isSlot: true
        }
      ]


    }
  },
  components: {
    'element-table': ElementTable,
  },
  methods: {
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    //查询病种
    getAdvertisementHealthMapDiseaseList(searchType) {

      this.post(this.api.healthMap.getAdvertisementHealthMapDiseaseList, {
        searchType: searchType
      }).then((res) => {
        if (res.data.code === '200') {
          this.diseaseDataSource = res.data.object
        }
      })
    },
    //查询主题
    getAdvertisementDiscOfLifeTheme(type) {
      this.post(this.api.healthMap.getAdvertisementDiscOfLifeTheme, {
        type: type
      }).then((res) => {
        if (res.data.code === '200') {
          this.themeDataSource = res.data.object
        }
      })
    },
    //查询慢病
    getAdvertisementThemeList() {
      this.post(this.api.healthMap.getAdvertisementThemeList).then((res) => {
        if (res.data.code === '200') {
          this.chronicDiseaseDataSource = res.data.object
        }
      })
    },

    // 广告类型
    changeAdType(val) {
      this.formdata.type = val;
      this.formdata.port = ''
      this.formdata.positionType = ''
      if (val === 2) {
        this.formdata.termOfValidity = '';
      }
      if (val === 1) {
        this.formdata.termOfValidity = '永久';
      }
      this.searchPort();
    },
    // 查询投放端口
    async searchPort() {
      const {data: res} = await this.post(this.api.banner.searchPort, {type: this.formdata.type});
      if (res.code === '200') {
        this.portList = res.object;
      }
    },
    // 省市区列表
    async selectChildren() {
      const {data: res} = await this.post(this.api.baseArea, {id: 0});
      if (res.code === '200') {
        this.provinceList = res.object;
      }
    },
    // 选择省
    changeProvice(index) {
      //   this.formdata.region = val
    },
    // 选择投放端口
    changePort(val) {
      this.formdata.port = val;
      this.formdata.positionType = ''
      this.getPositionTypeList();
      if (val === 3) {
        this.placeholderText = '请输入B端客户名称搜索（总店）';
      }
      if (val === 2 || val === 4) {
        this.placeholderText = '请输入执业机构名称搜索';
      }
    },
    // 根据端口搜索广告位置列表
    async getPositionTypeList() {
      const {data: res} = await this.post(this.api.banner.getPositionType, {
        type: this.formdata.type,
        port: this.formdata.port
      })
      if (res.code === '200') {
        this.positionTypeList = res.object;
        this.positionTypeList.map(item => {
          if (item.type === 15) {
            this.positionChildTypeList = item.positionTypeResponseDto;
          }
        })
      }
    },
    handleOption(op, index) {
      switch (op) {
        case 'add_disease_edit':
          if (!this.inputData.inputDiseasesId) {
            this.$message.error('请选择病种')
          } else {

            this.inputData.inputTargetObj.forEach(x => {
              this.formdata.advertisementRelations.push({
                relationParentId: this.inputData.inputDiseasesId,
                relationParentName: this.diseaseDataSource.find(o => o.id === this.inputData.inputDiseasesId).name,
                relationId: x.id,
                relationName: x.projectName
              })
            })
            this.inputData.inputDiseasesId = ''
            this.inputData.inputTargetObj = []
          }
          break
        case 'del_disease_edit':
          this.formdata.advertisementRelations.splice(index, 1)
          break
        case 'add_point':
          if (!this.pointerData.pointerType) {
            this.$message.error('请选择指征类型')
          } else if (!this.pointerData.themeObj) {
            this.$message.error('请选择主题')
          } else if (this.pointerData.pointObj.length === 0) {
            this.$message.error('请选择指征')
          } else {
            this.pointerData.pointObj.forEach(x => {
              this.formdata.advertisementRelations.push({
                pointTypeName: this.pointerData.pointerType.name,
                relationType: this.pointerData.pointerType.id,
                relationParentId: this.pointerData.themeObj.id,
                relationParentName: this.pointerData.themeObj.themeName,

                relationId: x.pointId,
                relationName: x.pointName,
              })
            })
            this.pointerData.pointerType = '',
              this.pointerData.themeObj = '',
              this.pointerData.pointObj = []
          }
          break
      }
    },
    //TODO 通过病种查询指标
    handleChangeDiseases(val) {
      this.inputData.inputTargetObj = []
      this.targetDataSource = this.diseaseDataSource.find(item => item.id === val).healthMapDiseaseTargets
    },
    //TODO 选择指征类型
    handleChangePoint(val) {
      this.pointerData.themeObj = ''
      this.pointerData.pointObj = ''
      this.getAdvertisementDiscOfLifeTheme(val.id)
    },
    //TODO 选择主题
    handleChangeTheme(val) {
      this.pointerData.pointObj = []
      if (val.type === 1) {
        this.pointerDataSource = val.discOfLifeBases.map(o => ({
          pointName: o.targetName,
          pointId: o.id
        }))
      } else if (val.type === 2) {
        this.pointerDataSource = val.discOfLifeScales.map(o => ({
          pointName: o.scaleName,
          pointId: o.id
        }))
      } else if (val.type === 3) {
        this.pointerDataSource = val.detectIndexes.map(o => ({
          pointName: o.indexName,
          pointId: o.id
        }))
      }

    },
    // 选择位置类型
    changePositionType(val) {
      this.formdata.advertisementRelations = []
      this.formdata.positionType = val;
      switch (val) {
        case 36:
          this.getAdvertisementDiscOfLifeTheme(3)
          break
        case 41:
          //查询病种
          this.getAdvertisementHealthMapDiseaseList(null)
          break;
        case 44:
          //查询病种
          this.getAdvertisementHealthMapDiseaseList(null)
          break;
        case 39:
          //查询病种
          this.getAdvertisementHealthMapDiseaseList(null)
          break;
        case 42:
          this.getAdvertisementHealthMapDiseaseList(2)
          break;
        case 43:
          this.getAdvertisementHealthMapDiseaseList(2)
          break;
        case 45:
          this.getAdvertisementThemeList()
          break;
        case 46:
          this.getAdvertisementThemeList()
          break;
        case 47:
          this.getAdvertisementThemeList()
          break;
        case 15:
          // 子类型
          this.getPositionTypeList();
          break
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    // 沃慧管
    beforeAvatarUpload1(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    // 详情图片地址
    handlePictureCardPreview(response, file, fileList, index) {
      let sortNum = 0
      if (this.advertisementImgDtos.length === 0) {
        sortNum = this.advertisementImgDtos.length + 1
      } else {
        let numArr = this.advertisementImgDtos.map(item => item.position)
        sortNum = Math.max(...numArr) + 1
      }

      this.advertisementImgDtos.push({
        id: null,
        position: sortNum,
        url: file.response.object[0],
        wide: '',
        high: '',
        link: ''
      })
    },
    // 沃慧管-详情图片地址
    handlePictureCardPreview1(response, file, fileList, index) {
      let sortNum = 0
      if (this.loveCustomersDtos.advertisementImgDtos.length === 0) {
        sortNum = this.loveCustomersDtos.advertisementImgDtos.length + 1
      } else {
        let numArr = this.loveCustomersDtos.advertisementImgDtos.map(item => item.position)
        sortNum = Math.max(...numArr) + 1
      }
      this.loveCustomersDtos.advertisementImgDtos.push({
        id: null,
        position: sortNum,
        url: file.response.object[0],
        wide: '',
        high: '',
        link: ''
      })
    },
    // 删除图片
    onremove(res, list) {
      if (res.response) {
        this.formdata.detailsImgUrl = this.formdata.detailsImgUrl.filter(ele => ele != res.response.object[0]);
        const i = this.advertisementImgDtos.findIndex(item => item.url == res.response.object[0]);
        this.advertisementImgDtos.splice(i, 1);
      } else {
        this.formdata.detailsImgUrl = this.formdata.detailsImgUrl.filter(ele => ele != res.url);
        const i = this.advertisementImgDtos.findIndex(item => item.url == res.url);
        this.advertisementImgDtos.splice(i, 1);
      }
    },
    // 沃慧管-删除图片
    onremove1(res, list) {
      if (res.response) {
        this.loveCustomersDtos.detailsImgUrl = this.loveCustomersDtos.detailsImgUrl.filter(ele => ele != res.response.object[0]);
        const i = this.loveCustomersDtos.advertisementImgDtos.findIndex(item => item.url == res.response.object[0]);
        this.loveCustomersDtos.advertisementImgDtos.splice(i, 1);
      } else {
        this.loveCustomersDtos.detailsImgUrl = this.loveCustomersDtos.detailsImgUrl.filter(ele => ele != res.url);
        const i = this.loveCustomersDtos.advertisementImgDtos.findIndex(item => item.url == res.url);
        this.loveCustomersDtos.advertisementImgDtos.splice(i, 1);
      }
    },
    // 图片限制
    onexceed(files, fileList) {
      this.$message.warning(`请最多上传${this.limitImgNum}个图片`);
    },
    // 沃慧管-图片限制
    onexceed1(files, fileList) {
      this.$message.warning(`请最多上传${this.limitImgNum}个图片`);
    },
    // 保存
    async submitForm() {
      if (this.formdata.positionType === 15) { // 一级必选,二级可选;如选二级,只传最后一个参数
        this.formdata.positionType = this.formdata.positionChildType ? this.formdata.positionChildType : this.formdata.positionType;
      }
      // 精准营销-用户端-投放客户区域
      if (this.formdata.type === 2 && this.formdata.port === 1) {
        this.regionList = this.tableDataSelect.map(v => v.region);
        if (this.regionList.length > 0) {
          let res = this.tableDataSelect;
          let item = res[res.length - 1];
          if (item.region === '') {
            this.$message.warning('请先选择投放区域!');
            return
          }
          if (new Set(this.regionList).size !== this.tableDataSelect.length) {
            this.$message.warning('不能投放相同客户区域!');
            return
          }
          this.formdata.region = this.regionList.join(',');
        } else {
          this.$message.warning('请添加客户区域!');
          return
        }
      }

      // 沃慧管：头部广告：6个，上传图片数量必须为偶数；首页广告：6个，上传图片数量必须为偶数
      if (this.formdata.positionType === 9 || this.formdata.port === 10) {
        if (this.advertisementImgDtos.length % 2 !== 0) {
          this.$message.warning('上传图片数量必须为偶数');
          return
        }
      }
      let arr = this.advertisementImgDtos.map(v => v.position)
      if (new Set(arr).size !== this.advertisementImgDtos.length) {
        this.$message.warning('图片排序不能相同!');
        return
      }
      // 已选客户 精准推送关联用户列表 如果是精准广告要绑定用户
      // 精准营销-医生端
      if (this.formdata.type === 2 && (this.formdata.port === 2 || this.formdata.port === 3 || this.formdata.port === 4)) {
        this.formdata.userIds = this.tableHaveCustomersList.map(item => item.id);
        if (this.formdata.userIds.length === 0) {
          this.$message.warning('添加或修改广告时必须分配用户');
          return
        }
      }
      let params = {}
      let subData = JSON.parse(JSON.stringify(this.formdata))

      if (subData.positionType === 41 || subData.positionType === 36 || subData.positionType === 45 || subData.positionType === 46 || subData.positionType === 47 || subData.positionType === 44 || subData.positionType === 39) {
        subData.advertisementRelations = subData.advertisementRelations.map(x => ({
          relationId: x
        }))
      }

      if (subData.type === 2 && subData.port === 3) {
        params = {
          advertisementImgDtos: this.advertisementImgDtos,
          ...subData,
          termOfValidity: subData.termOfValidity === '永久' ? -1 : subData.termOfValidity,
          loveCustomersDtos: [this.loveCustomersDtos]
        }
      } else {
        params = {
          advertisementImgDtos: this.advertisementImgDtos,
          ...subData,
          termOfValidity: this.formdata.termOfValidity === '永久' ? -1 : this.formdata.termOfValidity
        }
      }
      console.log('提交数据', params)
      this.$refs.formdataRef.validate(async (valid) => {
        if (valid) {
          // if (subData.advertisementRelations.length === 0) {
          //   this.$message.error('请完善数据')
          //   return
          // }
          const {data: res} = await this.post(this.api.banner.saveOrdinaryAdvertisement, params);
          if (res.code === '200') {
            this.$message.success('保存成功!');
            this.modalClose();
            this.$parent.getList();
          }
        }
      })
    },
    // 查询详情
    async getQueryByIdDetail() {
      const {data: res} = await this.post(this.api.banner.getQueryByIdDetail, {id: this.bannerObj.id});
      if (res.code === '200') {
        let resData = res.object;
        this.formdata = resData;
        this.formdata.termOfValidity = resData.termOfValidity === -1 ? '永久' : resData.termOfValidity;
        if (resData.positionType.positionTypeResponseDto) {
          let dto = resData.positionType.positionTypeResponseDto;
          this.formdata.positionChildType = dto[0].type;
        }
        this.formdata.positionType = resData.positionType.type;

        // 精准营销-用户端
        if (this.formdata.type === 2 && this.formdata.port === 1) {
          let regionSplit = resData.region.split(',');
          let regionArray = regionSplit.map(v => ({region: Number(v)}));
          this.tableDataSelect = regionArray;
          this.selectChildren(); // 回显省
        }

        this.searchPort(); // 回显投放端口
        // 回显位置类型
        this.formdata.port = resData.port;
        this.getPositionTypeList();


        this.formdata.detailsImgUrl = resData.advertisementImgDtos;
        this.formdata.detailsImg = [];

        resData.advertisementImgDtos.forEach(ele => {
          let op = {};
          op.name = ele.url;
          op.url = ele.url;
          op.position = ele.position;
          this.formdata.detailsImg.push(op);
        })

        this.advertisementImgDtos = this.formdata.detailsImgUrl;
        // 精准营销-沃慧管
        if (this.formdata.type === 2 && this.formdata.port === 3) {
          if (resData.loveCustomersDtos.length > 0) {
            this.checked = true;
            this.loveCustomersDtos = resData.loveCustomersDtos[0];
            this.loveCustomersDtos.detailsImgUrl = resData.loveCustomersDtos[0].advertisementImgDtos;
            this.loveCustomersDtos.detailsImg = [];
            resData.loveCustomersDtos[0].advertisementImgDtos.forEach(ele => {
              let op = {}
              op.name = ele.url;
              op.url = ele.url;
              op.position = ele.position;
              this.loveCustomersDtos.detailsImg.push(op);
            })
            this.loveCustomersDtos.advertisementImgDtos = this.loveCustomersDtos.detailsImgUrl;
          } else {
            this.loveCustomersDtos.positionType = -1;
          }
        }
        // 精准营销-医生端,5G智慧数字医疗系统,机构pad
        if (this.formdata.type === 2 && (this.formdata.port === 2 || this.formdata.port === 3 || this.formdata.port === 4)) {
          this.searchCustomersList();
          this.searchHaveCustomersList();
        }

        //TODO 新增逻辑
        if (this.formdata.positionType === 41 || this.formdata.positionType === 44 || this.formdata.positionType === 39) {
          this.getAdvertisementHealthMapDiseaseList(null)
          this.formdata.advertisementRelations = this.formdata.advertisementRelations.map(item => item.relationId)
        } else if (this.formdata.positionType === 36) {
          this.getAdvertisementDiscOfLifeTheme(3)
          this.formdata.advertisementRelations = this.formdata.advertisementRelations.map(item => item.relationId)
        } else if (this.formdata.positionType === 42 || this.formdata.positionType === 43) {
          this.getAdvertisementHealthMapDiseaseList(2)
        } else if (this.formdata.positionType === 45 || this.formdata.positionType === 46 || this.formdata.positionType === 47) {
          this.getAdvertisementThemeList()
          this.formdata.advertisementRelations = this.formdata.advertisementRelations.map(item => item.relationId)
        }
        console.log('详情', this.formdata)
      }
    },
    // 新增客户区域
    addArea() {
      this.selectChildren()
      let res = this.tableDataSelect;
      if (res.length > 0) {
        let item = res[res.length - 1]
        if (item.region === '') {
          this.$message.warning('请先选择投放区域!');
          return
        }
        this.tableDataSelect.push({region: '', name: ''});
      } else {
        this.tableDataSelect.push({region: '', name: ''});
      }
    },
    // 删除客户区域
    delArea(table, index) {
      if (table.length == 1) {
        this.$message.warning('至少保留一项');
        return
      } else {
        table.splice(index, 1);
      }
    },
    async querySearchAsync(queryString, callback) {
      const {data: res} = await this.post(this.api.banner.searchHospitalByName, {
        pageIndex: 0,
        pageSize: 10,
        hospitalName: queryString
      })
      let list = [{}];
      for (let i of res.object) {
        i.value = i.name;  // 将想要展示的数据作为value
      }
      list = res.object;
      callback(list);
    },

    // 选择医院名称
    handleSelect(item) {
      this.formdata.hospitalId = item.id;
      this.formdata.hospitalName = item.name;
    },
    // 查询投放客户列表
    async searchCustomersList() {
      if (this.formdata.port === '') {
        this.$message.warning('请先选择投放端口!');
        return
      }
      if (this.formdata.organName === '') {
        this.$message.warning('请输入如投放客户!');
        return
      }
      const {data: res} = await this.post(this.api.banner.searchCustomersListByName, {
        id: this.bannerObj ? this.bannerObj.id : '',
        pageIndex: 0,
        pageSize: 50,
        organName: this.formdata.organName,
        port: this.formdata.port,
      })
      if (res.code === '200') {
        this.tableCustomersList = res.object;
      }
    },
    // 投放广告此操作
    isPutAd(row, op, index) {
      switch (op) {
        case 'sure': // 投放
          this.tableCustomersList.splice(index, 1);
          this.tableHaveCustomersList.push(row);
          break;
        case 'cancel': // 取消投放
          this.tableHaveCustomersList.splice(index, 1);
          break;
      }
    },
    // 查询已选客户列表
    async searchHaveCustomersList() {
      const {data: res} = await this.post(this.api.banner.searchHaveCustomersList, {
        id: this.bannerObj ? this.bannerObj.id : '',
        pageIndex: 0,
        pageSize: 50,
        port: this.formdata.port
      })
      if (res.code === '200') {
        this.tableHaveCustomersList = res.object;
      }
    },
    // 对应b端客户使用爱追客的用户对应个人版pp广告投放
    changeChecked(val) {
      this.checked = val;
      if (val) {
        this.loveCustomersDtos.positionType = 4;
      } else {
        this.loveCustomersDtos.positionType = -1;
        this.loveCustomersDtos.detailsImgUrl = [];
        this.loveCustomersDtos.detailsImg = [];
        this.loveCustomersDtos.advertisementImgDtos = [];
      }
    }
  },
  created() {

    if (this.bannerObj) {
      this.title = '编 辑';
      this.getQueryByIdDetail();
      this.isDisabled = true;
      this.isFormDisabled = false;
      if (this.isDetail) {
        this.title = '详 情';
        this.isFormDisabled = true;
      }
    }
  }
}
</script>

<style lang="scss">
.setImg {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.table-select-reagion {
  tbody {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
